import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Image,
  ScrollView,
  Dimensions,
  SafeAreaView,
  ActivityIndicator,
  Animated,
  Alert,
  Modal,
  PanResponder,
} from 'react-native';
import CheckBox from '@react-native-community/checkbox';
import { wp, hp } from '../utils/layout';
import { FONT_SIZES } from '../utils/fontSize';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { saveTokens } from '../utils/authRequest';

const { height: SCREEN_HEIGHT } = Dimensions.get('window');

const RegisterScreen = ({ navigation }: any) => {
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [checked, setChecked] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [phoneError, setPhoneError] = useState('');
  const [codeError, setCodeError] = useState('');
  const [inputFocus, setInputFocus] = useState({
    phone: false,
    code: false,
  });
  const [buttonScale] = useState(new Animated.Value(1));
  const countdownRef = useRef<NodeJS.Timeout>();
  const [showSlider, setShowSlider] = useState(false);
  const [sliderPassed, setSliderPassed] = useState(false);
  const [sliderX] = useState(new Animated.Value(0));
  const SLIDER_WIDTH = 280;
  const SLIDER_HEIGHT = 40;
  const SLIDER_BTN_SIZE = 36;

  useEffect(() => {
    return () => {
      if (countdownRef.current) {
        clearInterval(countdownRef.current);
      }
    };
  }, []);

  useEffect(() => {
    if (countdown > 0) {
      countdownRef.current = setInterval(() => {
        setCountdown(prev => prev - 1);
      }, 1000);
    } else if (countdownRef.current) {
      clearInterval(countdownRef.current);
    }
    return () => {
      if (countdownRef.current) {
        clearInterval(countdownRef.current);
      }
    };
  }, [countdown]);

  const validatePhone = (phoneNumber: string) => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phoneNumber);
  };

  const handlePhoneChange = (text: string) => {
    // 只允许输入数字
    const numericValue = text.replace(/[^0-9]/g, '');
    setPhone(numericValue);
    setPhoneError('');
  };

  const handleGetCode = async () => {
    if (!validatePhone(phone)) {
      setPhoneError('请输入正确的手机号');
      return;
    }

    try {
      setIsLoading(true);
      const response = await fetch('http://172.20.10.6:3001/api/auth/send-code', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone })
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.message || '验证码发送失败');
      setCountdown(60);
      Alert.alert('成功', '验证码已发送');
    } catch (error) {
      Alert.alert('错误', error.message || '验证码发送失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const validateInputs = () => {
    let isValid = true;

    if (!validatePhone(phone)) {
      setPhoneError('请输入正确的手机号');
      isValid = false;
    }

    if (!code) {
      setCodeError('请输入验证码');
      isValid = false;
    } else if (code.length !== 6) {
      setCodeError('验证码长度不正确');
      isValid = false;
    }

    if (!checked) {
      Alert.alert('提示', '请阅读并同意用户协议');
      isValid = false;
    }

    return isValid;
  };

  const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onMoveShouldSetPanResponder: () => true,
    onPanResponderMove: (evt, gestureState) => {
      let x = Math.max(0, Math.min(gestureState.dx, SLIDER_WIDTH - SLIDER_BTN_SIZE));
      sliderX.setValue(x);
    },
    onPanResponderRelease: (evt, gestureState) => {
      if (gestureState.dx > SLIDER_WIDTH - SLIDER_BTN_SIZE - 5) {
        // 滑动到最右侧
        Animated.timing(sliderX, {
          toValue: SLIDER_WIDTH - SLIDER_BTN_SIZE,
          duration: 100,
          useNativeDriver: false,
        }).start(() => {
          setShowSlider(false);
          setSliderPassed(true);
          sliderX.setValue(0);
          handleRegister();
        });
      } else {
        // 未滑到最右，回到起点
        Animated.timing(sliderX, {
          toValue: 0,
          duration: 200,
          useNativeDriver: false,
        }).start();
      }
    },
  });

  const handleRegisterPress = () => {
    if (!validateInputs()) return;
    setShowSlider(true); // 弹出滑块
  };

  const handleRegister = async () => {
    if (!validateInputs()) {
      return;
    }

    // 按钮缩放动画
    Animated.sequence([
      Animated.timing(buttonScale, {
        toValue: 0.95,
        duration: 100,
        useNativeDriver: true,
      }),
      Animated.timing(buttonScale, {
        toValue: 1,
        duration: 100,
        useNativeDriver: true,
      }),
    ]).start();

    setIsLoading(true);
    try {
      const response = await fetch('http://172.20.10.6:3000/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, code, password: '123456' })
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.message || '注册失败');
      await saveTokens(data.accessToken, data.refreshToken);
      await AsyncStorage.setItem('userInfo', JSON.stringify(data.user));
      Alert.alert('成功', '注册成功', [
        {
          text: '确定',
          onPress: () => navigation.replace('AccountLogin'),
        },
      ]);
    } catch (error) {
      Alert.alert('错误', error.message || '注册失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      <KeyboardAvoidingView
        style={styles.flex1}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      >
        <View style={styles.container}>
          {/* 顶部栏 */}
          <View style={styles.header}>
            <TouchableOpacity onPress={() => navigation.goBack()}>
              <Text style={styles.back}>{'<'}</Text>
            </TouchableOpacity>
          </View>
          <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled">
            {/* 标题 */}
            <Text style={styles.title}>快速注册</Text>
            <Text style={styles.subtitle}>未注册手机号将自动注册并登录</Text>
            
            {/* 手机号输入 */}
            <View style={[
              styles.inputBox,
              inputFocus.phone && styles.inputBoxFocused,
              phoneError && styles.inputBoxError
            ]}>
              <Image source={{ uri: 'https://img.icons8.com/color/48/000000/iphone-x.png' }} style={styles.inputIconImg} />
              <Text style={styles.inputPrefix}>+86</Text>
              <TextInput
                style={styles.input}
                placeholder="请输入11位手机号"
                placeholderTextColor="#bbb"
                keyboardType="phone-pad"
                maxLength={11}
                value={phone}
                onChangeText={handlePhoneChange}
                onFocus={() => setInputFocus(prev => ({ ...prev, phone: true }))}
                onBlur={() => setInputFocus(prev => ({ ...prev, phone: false }))}
              />
            </View>
            {phoneError ? <Text style={styles.errorText}>{phoneError}</Text> : null}

            {/* 验证码输入 */}
            <View style={[
              styles.inputBox,
              inputFocus.code && styles.inputBoxFocused,
              codeError && styles.inputBoxError
            ]}>
              <Image source={{ uri: 'https://img.icons8.com/fluency/48/lock-2.png' }} style={styles.inputIconImg} />
              <TextInput
                style={[styles.input, { flex: 1 }]}
                placeholder="请输入验证码"
                placeholderTextColor="#bbb"
                keyboardType="number-pad"
                maxLength={6}
                value={code}
                onChangeText={(text) => {
                  setCode(text);
                  setCodeError('');
                  if (text.length === 6) {
                    setChecked(true);
                  }
                }}
                onFocus={() => setInputFocus(prev => ({ ...prev, code: true }))}
                onBlur={() => setInputFocus(prev => ({ ...prev, code: false }))}
              />
              <TouchableOpacity 
                style={[styles.codeBtn, countdown > 0 && styles.codeBtnDisabled]} 
                onPress={handleGetCode}
                disabled={countdown > 0 || isLoading}
              >
                <Text style={[styles.codeBtnText, countdown > 0 && styles.codeBtnTextDisabled]}>
                  {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                </Text>
              </TouchableOpacity>
            </View>
            {codeError ? <Text style={styles.errorText}>{codeError}</Text> : null}

            <TouchableOpacity style={styles.codeTip}>
              <Text style={styles.codeTipText}>收不到验证码</Text>
            </TouchableOpacity>

            {/* 注册按钮 */}
            <Animated.View style={[styles.registerBtnContainer, { transform: [{ scale: buttonScale }] }]}>
              <TouchableOpacity 
                style={[styles.registerBtn, isLoading && styles.registerBtnDisabled]} 
                onPress={handleRegisterPress}
                disabled={isLoading}
              >
                {isLoading ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <Text style={styles.registerBtnText}>注册</Text>
                )}
              </TouchableOpacity>
            </Animated.View>
          </ScrollView>
        </View>
        {/* 协议勾选 固定底部，放在ScrollView外部 */}
        <View style={styles.protocolBox}>
          <CheckBox
            value={checked}
            onValueChange={setChecked}
            boxType="square"
            tintColors={{ true: '#1976ff', false: '#bbb' }}
          />
          <Text style={styles.protocolText}>
            我已阅读并同意AI智能医疗辅助系统 用户协议、隐私政策 以及儿童个人信息保护政策
          </Text>
        </View>
        {/* 自定义滑块验证 Modal */}
        <Modal
          visible={showSlider}
          transparent
          animationType="fade"
          onRequestClose={() => setShowSlider(false)}
        >
          <View style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'center', alignItems: 'center' }}>
            <View style={{ backgroundColor: '#fff', padding: 20, borderRadius: 8, alignItems: 'center' }}>
              <Text style={{ marginBottom: 16, fontSize: 16, textAlign: 'center' }}>请按住滑块，拖动到最右边</Text>
              <View style={{ width: SLIDER_WIDTH, height: SLIDER_HEIGHT, backgroundColor: '#f0f0f0', borderRadius: 20, justifyContent: 'center' }}>
                <Animated.View
                  {...panResponder.panHandlers}
                  style={{
                    position: 'absolute',
                    left: sliderX,
                    width: SLIDER_BTN_SIZE,
                    height: SLIDER_BTN_SIZE,
                    borderRadius: SLIDER_BTN_SIZE / 2,
                    backgroundColor: '#1976ff',
                    justifyContent: 'center',
                    alignItems: 'center',
                    zIndex: 2,
                    elevation: 2,
                  }}
                >
                  <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: 18 }}>{'>>'}</Text>
                </Animated.View>
                <View style={{ position: 'absolute', left: 0, top: 0, width: SLIDER_WIDTH, height: SLIDER_HEIGHT, justifyContent: 'center', alignItems: 'center' }}>
                  <Text style={{ color: '#888' }}>拖动滑块完成验证</Text>
                </View>
              </View>
              <TouchableOpacity onPress={() => setShowSlider(false)} style={{ marginTop: 16 }}>
                <Text style={{ color: '#1976ff', textAlign: 'center' }}>取消</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Modal>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff',
  },
  flex1: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingHorizontal: 24,
    paddingTop: 40,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 40,
    marginBottom: 0,
    marginTop: 0,
  },
  back: {
    fontSize: 22,
    color: '#222',
    fontWeight: 'bold',
    marginLeft: 0,
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: 'flex-start',
    minHeight: 0,
    paddingTop: 0,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#222',
    textAlign: 'center',
    marginTop: 60,
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 14,
    color: '#888',
    textAlign: 'center',
    marginBottom: 32,
  },
  inputBox: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f5f6fa',
    borderRadius: 24,
    paddingHorizontal: 16,
    marginBottom: 20,
    height: 48,
    width: '100%',
  },
  inputBoxFocused: {
    borderWidth: 1,
    borderColor: '#1976ff',
    backgroundColor: '#fff',
  },
  inputBoxError: {
    borderWidth: 1,
    borderColor: '#ff4d4f',
    backgroundColor: '#fff',
  },
  inputIconImg: {
    width: 20,
    height: 20,
    resizeMode: 'contain',
    marginRight: 8,
  },
  inputPrefix: {
    fontSize: 16,
    color: '#222',
    marginRight: 8,
  },
  input: {
    flex: 1,
    fontSize: 16,
    color: '#222',
    minWidth: 0,
  },
  codeBtn: {
    backgroundColor: '#fff',
    borderColor: '#1976ff',
    borderWidth: 1,
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 4,
    marginLeft: 8,
    height: 32,
    justifyContent: 'center',
    alignItems: 'center',
  },
  codeBtnDisabled: {
    borderColor: '#bbb',
    backgroundColor: '#f5f5f5',
  },
  codeBtnText: {
    color: '#1976ff',
    fontSize: 14,
  },
  codeBtnTextDisabled: {
    color: '#bbb',
  },
  codeTip: {
    alignSelf: 'flex-end',
    marginBottom: 0,
    marginTop: -12,
  },
  codeTipText: {
    color: '#1976ff',
    fontSize: 14,
  },
  registerBtnContainer: {
    width: '100%',
    marginBottom: 32,
    marginTop: 0,
  },
  registerBtn: {
    backgroundColor: '#1976ff',
    borderRadius: 24,
    height: 48,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
  },
  registerBtnDisabled: {
    opacity: 0.8,
  },
  registerBtnText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  protocolBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 24,
    marginTop: 'auto',
    paddingHorizontal: 0,
  },
  protocolText: {
    fontSize: 12,
    color: '#bbb',
    marginLeft: 8,
    flex: 1,
    lineHeight: 18,
  },
  errorText: {
    color: '#ff4d4f',
    fontSize: 12,
    marginTop: -12,
    marginBottom: 12,
    marginLeft: 16,
  },
});

export default RegisterScreen; 